import datetime

from django.db import models
from django.db.models import Max
from office.models import Office
from users.models import UserInfo

CASE_TYPE = (
    (1, '民事'),
    (2, '刑事'),
    (3, '行政'),
    (4, '刑附民'),
    (5, '刑事自诉'),
    (6, '仲裁'),
    (7, '执行'),
)

CASE_CODE = "祥({})[{}]{}"


def get_case_format(case_type, year):
    if case_type == 1:
        case_name = '民'
    elif case_type == 2:
        case_name = '刑'
    elif case_type == 3:
        case_name = '行'
    elif case_type == '4':
        case_name = '刑民'
    elif case_type == '5':
        case_name = '刑自'
    elif case_type == '6':
        case_name = '裁'
    elif case_type == '7':
        case_name = '执'
    else:
        case_name = '民'

    code = "祥{}[{}]".format(case_name, year)
    return code


class Case(models.Model):
    """案件登记"""
    code = models.CharField(verbose_name='存档编号', max_length=32, blank=True, null=True)
    client = models.CharField(verbose_name='委托人', max_length=64)
    telephone = models.CharField(verbose_name='电话', max_length=32, blank=True, null=True)
    party = models.CharField(verbose_name='当事人', max_length=64)
    oppo_party = models.CharField(verbose_name='对方当事人', max_length=128, blank=True, null=True)
    case_type = models.IntegerField(verbose_name='案件类型', choices=CASE_TYPE)
    recv_lawyer = models.CharField(verbose_name='收案人', max_length=32, blank=True, null=True)
    reason = models.CharField(verbose_name='案由', max_length=128, blank=True, null=True)
    recv_time = models.DateField(verbose_name='收案时间', blank=True, null=True)
    court = models.CharField(verbose_name='管辖法院', max_length=64, blank=True, null=True)
    level = models.CharField(verbose_name='审级', max_length=16, blank=True, null=True)
    lead_lawyer = models.ForeignKey(UserInfo, verbose_name='主办律师', related_name="cases", blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    assist_lawyer = models.ForeignKey(UserInfo, verbose_name='出庭律师', related_name="assist_cases", blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    third_lawyer = models.ForeignKey(UserInfo, verbose_name='出庭律师', related_name="third_cases", blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    register_time = models.DateField(verbose_name='立案时间', blank=True, null=True)
    open_time = models.DateField(verbose_name='开庭时间', blank=True, null=True)
    end_time = models.DateField(verbose_name='结案时间', blank=True, null=True)
    case_num = models.CharField(verbose_name='案号', max_length=32, blank=True, null=True)
    comment = models.CharField(verbose_name='案件小结', max_length=512, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    archive_flag = models.BooleanField(verbose_name="归档", default=False)
    openid = models.CharField(verbose_name='微信ID', max_length=120,  blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '案件登记'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls, case_type):
        year = datetime.datetime.now().strftime('%Y')
        format_code = get_case_format(case_type, year)
        max_code = cls.objects.filter(code__startswith=format_code).aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = "{}{}".format(format_code, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(format_code, num)
            return code

    def save(self, *args, **kwargs):
        if self.code == "" or self.code is None:
            code = self.__class__.get_max_code(self.case_type)
            self.code = code

        return super().save(*args, **kwargs)


class CaseFile(models.Model):
    """案件资料"""
    case = models.ForeignKey(Case, verbose_name="案件名称", related_name="files",  blank=True, null=True, on_delete=models.CASCADE)
    name = models.CharField(verbose_name="文件名称", max_length=256, blank=True, null=True)
    file = models.FileField(verbose_name='文件', upload_to='case/', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '案件资料'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class Letter(models.Model):
    """申请律所函"""
    code = models.CharField(verbose_name='编号', max_length=32, blank=True, null=True)
    case = models.ForeignKey(Case, verbose_name='案件', related_name="letters", on_delete=models.CASCADE, db_constraint=False)
    court = models.CharField(verbose_name='针对院所', max_length=64, blank=True, null=True)
    level = models.CharField(verbose_name='审级', max_length=16, blank=True, null=True)
    client = models.CharField(verbose_name='委托人', max_length=64)
    party = models.CharField(verbose_name='当事人', max_length=64)
    lawyer = models.CharField(verbose_name='指派律师', max_length=64, blank=True, null=True)
    reason = models.CharField(verbose_name='案由', max_length=128, blank=True, null=True)
    office_name = models.CharField(verbose_name='律所', max_length=128, blank=True, null=True)
    apply_confirm = models.BooleanField(verbose_name='申请确认', blank=True, null=True)
    apply_time = models.DateTimeField(verbose_name='申请时间', blank=True, null=True)
    stamp_confirm = models.BooleanField(verbose_name='盖章确认', blank=True, null=True)
    stamp_time = models.DateTimeField(verbose_name='盖章时间', blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    stamp_user = models.ForeignKey(UserInfo, verbose_name='盖章人', related_name="stampusers", blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '申请律所函'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls, case_code):
        max_code = cls.objects.filter(code__startswith=case_code).aggregate(max_code=Max("code"))
        print(max_code, case_code)
        max_value = max_code['max_code']
        if max_value is None:
            num = '01'
            code = "{}({})".format(case_code, num)
            return code
        else:
            num = str(int(max_value[-3:-1]) + 1).rjust(2, '0')
            print(case_code, num)
            code = '{0}({1})'.format(case_code, num)
            return code

    def save(self, *args, **kwargs):
        if self.apply_confirm:
            if self.code == "" or self.code is None:
                code = self.__class__.get_max_code(self.case)
                self.code = code

            if self.apply_time is None:
                self.apply_time = datetime.datetime.now()

        if self.office_name is None:
            office = Office.objects.first()
            if office:
                self.office_name = office.name

        if self.stamp_confirm:
            if self.stamp_time is None:
                self.stamp_time = datetime.datetime.now()

        return super().save(*args, **kwargs)


class Introduce(models.Model):
    """专用介绍信"""
    code = models.CharField(verbose_name='编号', max_length=32, blank=True, null=True)
    case = models.ForeignKey(Case, verbose_name='案件', related_name="introduces", on_delete=models.CASCADE, db_constraint=False)
    court = models.CharField(verbose_name='针对机关', max_length=64, blank=True, null=True)
    party = models.CharField(verbose_name='当事人', max_length=64)
    lawyer = models.CharField(verbose_name='指派律师', max_length=64, blank=True, null=True)
    cert_no = models.CharField(verbose_name='执业证号', max_length=128, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=128, blank=True, null=True)
    telephone = models.CharField(verbose_name='联系电话', max_length=64, blank=True, null=True)
    reason = models.CharField(verbose_name='案由', max_length=128, blank=True, null=True)
    office_name = models.CharField(verbose_name='律所', max_length=128, blank=True, null=True)
    apply_confirm = models.BooleanField(verbose_name='申请确认', blank=True, null=True)
    apply_time = models.DateTimeField(verbose_name='申请时间', blank=True, null=True)
    stamp_confirm = models.BooleanField(verbose_name='盖章确认', blank=True, null=True)
    stamp_time = models.DateTimeField(verbose_name='盖章时间', blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    stamp_user = models.ForeignKey(UserInfo, verbose_name='盖章人', related_name="stmpusers", blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '专用介绍信'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls, case_code):
        max_code = cls.objects.filter(code__startswith=case_code).aggregate(max_code=Max("code"))
        print(max_code, case_code)
        max_value = max_code['max_code']
        if max_value is None:
            num = '01'
            code = "{}({})".format(case_code, num)
            return code
        else:
            num = str(int(max_value[-3:-1]) + 1).rjust(2, '0')
            print(case_code, num)
            code = '{0}({1})'.format(case_code, num)
            return code

    def save(self, *args, **kwargs):
        if self.apply_confirm:
            if self.code == "" or self.code is None:
                code = self.__class__.get_max_code(self.case)
                self.code = code

            if self.apply_time is None:
                self.apply_time = datetime.datetime.now()

        if self.office_name is None:
            office = Office.objects.first()
            if office:
                self.office_name = office.name

        if self.stamp_confirm:
            if self.stamp_time is None:
                self.stamp_time = datetime.datetime.now()

        return super().save(*args, **kwargs)


class CriminalIntroduce(models.Model):
    """独立会见介绍信"""
    code = models.CharField(verbose_name='编号', max_length=32, blank=True, null=True)
    court = models.CharField(verbose_name='针对机关', max_length=64, blank=True, null=True)
    party = models.CharField(verbose_name='当事人', max_length=64)
    lawyer = models.CharField(verbose_name='指派律师', max_length=64, blank=True, null=True)
    cert_no = models.CharField(verbose_name='执业证号', max_length=128, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=128, blank=True, null=True)
    telephone = models.CharField(verbose_name='联系电话', max_length=64, blank=True, null=True)
    reason = models.CharField(verbose_name='案由', max_length=128, blank=True, null=True)
    office_name = models.CharField(verbose_name='律所', max_length=128, blank=True, null=True)
    apply_confirm = models.BooleanField(verbose_name='申请确认', blank=True, null=True)
    apply_time = models.DateTimeField(verbose_name='申请时间', blank=True, null=True)
    stamp_confirm = models.BooleanField(verbose_name='盖章确认', blank=True, null=True)
    stamp_time = models.DateTimeField(verbose_name='盖章时间', blank=True, null=True)
    stamp_user = models.ForeignKey(UserInfo, verbose_name='盖章人', related_name="users", blank=True, null=True,
                                   on_delete=models.SET_NULL, db_constraint=False)
    user = models.ForeignKey(UserInfo, verbose_name='录入人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '刑事介绍信'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        case_code = datetime.datetime.now().strftime('[%Y]')
        case_code = str('祥(刑)') + case_code
        max_code = cls.objects.filter(code__startswith=case_code).aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = "{0}{1}".format(case_code, num)
            return code
        else:

            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(case_code, num)
            return code

    def save(self, *args, **kwargs):

        if self.apply_confirm:
            if self.code == "" or self.code is None:
                code = self.__class__.get_max_code()
                self.code = code

            if self.apply_time is None:
                self.apply_time = datetime.datetime.now()

        if self.office_name is None:
            office = Office.objects.first()
            if office:
                self.office_name = office.name

        if self.stamp_confirm:
            if self.stamp_time is None:
                self.stamp_time = datetime.datetime.now()

        return super().save(*args, **kwargs)


class Progress(models.Model):
    """案件进度配置"""
    name = models.CharField(verbose_name='进度名称', max_length=64, blank=True, null=True)
    parent = models.ForeignKey(verbose_name='父级', to='self', related_name='children', null=True, blank=True,
                               on_delete=models.SET_NULL, db_constraint=False)
    case_type = models.IntegerField(verbose_name='案件类型', choices=CASE_TYPE)
    is_final = models.BooleanField(verbose_name='案件终止标志', default=False)
    sort = models.IntegerField(verbose_name="顺序", blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '案件进度配置'
        verbose_name_plural = verbose_name
        ordering = ["case_type", "sort"]


class CaseProgress(models.Model):
    """案件进度"""
    CONFIRM = (
        (0, '待确认'),
        (1, '已确认'),
    )
    case = models.ForeignKey(Case, verbose_name="案件名称", on_delete=models.CASCADE, related_name="progresses", db_constraint=False)
    progress = models.ForeignKey(Progress, verbose_name="案件进度", on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    confirm = models.IntegerField(verbose_name='确认', blank=True, null=True, choices=CONFIRM)
    memo = models.CharField(verbose_name="说明", max_length=512, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.case

    class Meta:
        verbose_name = '案件进度'
        verbose_name_plural = verbose_name
        ordering = ["add_time"]


class Reason(models.Model):
    """案由"""
    name = models.CharField(verbose_name="案由", max_length=128)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '案件缘由'
        verbose_name_plural = verbose_name
        ordering = ["id"]


class CustomerCase(models.Model):
    """客户案件列表"""
    openid = models.CharField(verbose_name='微信ID', max_length=120, blank=True, null=True)
    case = models.ForeignKey(Case, verbose_name='案件', related_name="customers", blank=True, null=True, db_constraint=False, on_delete=models.CASCADE)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '客户案件'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


